import Vue 			from 'vue'
import util 		from '../../util'
import axios 		from 'axios'
import { Toast,Dialog } 	from 'vant';
Vue.use(Toast,Dialog);

export default {
	name: 'buyType',
	data(){
		return {
			name:'',			//购买的币种名称
			account:0,			//购买币种数量
			amountOfMoney:0,	//购买金额
			userName:'',		//当前实名认证用户名
			OTCWorkTime:'',		//OTC服务时间
			list:[],
			loading:false,		//按钮是否加载中
			bank_flow_status:2,	//银行卡流水审核状态  0:未提交 1:审核中  2:审核成功  3:审核失败
			error:false,
			onceDialog:false,	//是否提示一次
			dialogChecked:false,//我已知晓
		}
	},
	methods:{
		next(orderId,state){
			//下一步
			// this.$router.replace({
			// 	path:'/orderDetail',
			// 	query:{
			// 		id:orderId,
			// 		pageState:1,
			// 		death:1
			// 	}
			// })
			let query = {
				death:1
			}
			if(state == 2 || state == 4){
				query.id = orderId;
				query.pageState = 1
			}else{
				query.orderId = orderId
			}
			this.$router.replace({
				path:(state==2 || state==4)?'/orderDetail':'/makeOrder',
				query:query
			})
		},
		showDialog(orderId,state){
			//历史交易未结束提示
			Dialog.confirm({
				title: this.$t('buyType-key1'),
				message: this.$t('buyType-key2'),
				className:'fullDialog2',
				cancelButtonColor:'#1989fa',
				confirmButtonText:this.$t('buyType-key3'),
				cancelButtonText:this.$t('cancel'),
				overlayClass:'sellType-mark'
			}).then(() => {
				this.next(orderId,state);
				console.log('confirm')
			}).catch(() => {
				console.log('cancel')
				this.loading = false;
			})
		},
		renderLocal(){
			//渲染可能的缓存数据
			let otcPayConfig = util.getStorage('otcPayConfig');
			let verifiedInfo = util.getStorage('verifiedInfo');
			if(otcPayConfig && verifiedInfo){
				otcPayConfig = JSON.parse(otcPayConfig);
				this.OTCWorkTime = otcPayConfig.otc_serve_desc;
				this.userName = JSON.parse(verifiedInfo).name;
				util.bridgeData(otcPayConfig.pay).then(list => {
					//若没有推荐，则默认第一个
					if(list.filter(item => item.isSelected).length === 0) list[0].isSelected = true;
					this.list = list;
				}).catch(error => {
					Toast(this.$t('dataErr'))
				})
			}
		},
		init(){
			//获取付款方式以及服务时间
			util.fetch(`${util.ajaxUrl}/site/otc-pay-config`,{}).then(res => {
				if(res.retCode === 0){
					this.OTCWorkTime = res.retData.otc_serve_desc;
					util.bridgeData(res.retData.pay).then(list => {
						//若没有推荐，则默认第一个
						if(list.filter(item => item.isSelected).length === 0) list[0].isSelected = true;
						this.list = list
					}).catch(error => {
						Toast(this.$t('dataErr'))
					})
					util.setStorage('otcPayConfig',res.retData)
				}else{
					Toast(res.retMsg || this.$t('noError'))
				}
			}).catch(error => {
				console.log(error)
			})
		},
		getUserName(){
			//获取用户名
			util.fetch(`${util.ajaxUrl}/user/verified-info`,{
				token:this.token || util.getToken()
			}).then(res => {
				if(res.retCode === 0){
					this.userName = res.retData.name;
					util.setStorage('verifiedInfo',res.retData)
				}else{
					Toast(res.retMsg || this.$t('noError'))
				}
			}).catch(error => {
				console.log(error)
			})
		},
		getPrice(){
			//获取每个B单价
			util.getPriceByName(this.name,1,this.account).then(price => {
				this.amountOfMoney = util.accMul(price,this.account).toFixed(2)
			}).catch(() => {
				Toast(this.$t('getPriceFail'))
			})
			setTimeout(() => {
				this.getPrice();
			},util.time)
		},
		clearStorage(){
			//非生产，可清除数据
			if(util.status != 4){
				window.localStorage.removeItem('makeOrderCount')
			}
		},
		dialogOnce(){
			//提示一次
			let local = window.localStorage.getItem('makeOrderCount');
			if(local){
				this.makeOrder();
			}else{
				this.onceDialog = true;
			}
		},
		goNext(){
			//去下单
			if(!this.dialogChecked) return
			window.localStorage.setItem('makeOrderCount',1);
			this.makeOrder();
		},
		makeOrder(){
			this.onceDialog = false;
			let _arr = this.list.filter(item => item.isSelected);
			if(_arr.length === 0) _arr = this.list[0];
			let _type = _arr[0].type;
			//若是银行卡，则检测是否已上传资金流水
			if(_type == 2 && this.bank_flow_status != 2){
				this.$router.replace({
					path:'/cardVerify',
					query:{
						death:1
					}
				})
				return
			}
			//下单接口
			this.loading = true;
			let params = {
				token:this.token || util.getToken(),
				orderusdt:this.account,					//购买币种数量
				in_type:_type==3?4:_type,				//下单类型  1:支付宝  2:银行卡  4:微信
				currency_id:this.name,					//购买币种名称
			};
			setTimeout(()=>{
				//点击确定
				util.fetch(`${util.ajaxUrl}/otc/inmoney`,params).then(res => {
					if(res && res.retCode == 0){
						setTimeout(() => {
							if(res && res.retData && res.retData.id){
								this.next(res.retData.id)
							}else{
								this.loading = false;
							}
						},500)
					}else if(res && res.retCode == -1){
						//弹窗(先判断订单状态)
						util.fetch(`${util.ajaxUrl}/otc/inmoney-detail`,{
							token:this.token || util.getToken(),
							id:res.retData.id
						}).then(xhr => {
							if(xhr.retCode === 0){
								this.showDialog(res.retData.id,xhr.retData.state)
							}else{
								Toast(xhr.retMsg || this.$t('noError'))
							}
							this.loading = false;
						}).catch(error => {
							console.log(error)
						})
					}else{
						this.loading = false;
						Toast(res.retMsg || this.$t('noError'))
					}
				}).catch(error => {
					this.loading = false;
					console.log(error)
				})
			},2000)
		},
		goChoice(_item){
			//是否选中
			this.list.map(item => {
				item.isSelected = item.type === _item.type?true:false
			})
		},
		goBack(){
			util.navigateBack(-1,this)
		},
		init0(){
			util.waitSDKReady().then(token => {
				this.token = token;
				let _query = this.$route.query;
				if(_query.name && _query.account){
					this.name = _query.name;
					this.account = _query.account;
					this.renderLocal();
					this.init();
					this.getUserName();
					this.getPrice();
				}else{
					Toast(this.$t('dataErr'))
				}
				//拿到token后检测用户是否已实名认证，防止flutter跳转过来的时候没检测实名认证状态
				// if(this.token){
				// 	util.checkRealName(this.token).then(retData => {
				// 		this.bank_flow_status = retData.bank_flow_status;
				// 		if(retData.kyc_status == 0){
				// 			//未认证
				// 			this.$router.push('/goRealName')
				// 		}else if(retData.kyc_status == 1 || retData.kyc_status == 3){
				// 			//审核中  审核驳回
				// 			this.$router.push('/realNameStatus')
				// 		}
				// 	}).catch(e => {
						
				// 	})
				// }
			}).catch((e) => {
				Toast(this.$t('getTokenFail'))
			})
		}
	},
	created() {
		this.init0();
		setTimeout(() => {
			//退出登录的时候native调用H5方法清除token缓存
			util.registerHandler('loginOutDeleteToken',res => {
				localStorage.removeItem('token');
			})
			util.callHandler('setStatusBarStyle',{
				style:'dark'
			})
			util.registerHandler('refreshCommonRequestWhenGoBackView',res => {
				this.init0();
				util.callHandler('setStatusBarStyle',{
					style:'dark'
				})
			})
		},500)
    }
}